#include <errno.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>

#define FIFOARG 1
#define FIFO_PERMS (S_IRWXU | S_IWGRP | S_IWOTH)
#define BLKSIZE PIPE_BUF


ssize_t r_write(int fd, void *buf, size_t size) {
	char *bufp;
	size_t bytestowrite;
	ssize_t byteswritten;
	size_t totalbytes;

	for (bufp = (char*)buf, bytestowrite = size, totalbytes = 0;
			bytestowrite > 0;
			bufp += byteswritten, bytestowrite -= byteswritten) {
		byteswritten = write(fd, bufp, bytestowrite);
		if ((byteswritten) == -1 && (errno != EINTR))
			return -1;
		if (byteswritten == -1)
			byteswritten = 0;
		totalbytes += byteswritten;
	}
	return totalbytes;
}




ssize_t r_read(int fd, void *buf, size_t size) {
	ssize_t retval;
	while (retval = read(fd, buf, size), retval == -1 && errno == EINTR) ;
	return retval;
}



int readwrite(int fromfd, int tofd) {
	char buf[BLKSIZE];
	int bytesread;

  if ((bytesread = r_read(fromfd, buf, BLKSIZE)) < 0)
		return -1;
  if (bytesread == 0)
		return 0;
	if (r_write(tofd, buf, bytesread) < 0)
		return -1;
	return bytesread;
}




int copyfile(int fromfd, int tofd) {
	int bytesread;
	int totalbytes = 0;

	while ((bytesread = readwrite(fromfd, tofd)) > 0)
		totalbytes += bytesread;
	return totalbytes;
}



int main (  int argc, char *argv[] )
{
	int requestfd;
	if ( argc != 2 )
	{
		fprintf( stderr, "usage: %s fifoname > logfile\n", argv[0] );
		return 1;
	}
	if((mkfifo(argv[FIFOARG],FIFO_PERMS) == -1) && (errno!=EEXIST))
	{
		perror("server failed to create a FIFO");
		return 1;
	}
	if( (requestfd=open(argv[FIFOARG],O_RDWR)) == -1 )
	{
		perror("server failed to open its FIFO");
		return 1;
	}
	copyfile(requestfd,STDOUT_FILENO);

	return 1;
}
